import { createSlice } from '@reduxjs/toolkit'
import { getKey, getQRCode, checkQRCode } from '@/views/login/service/login'

import { createAsyncThunk } from '@reduxjs/toolkit'

export const fetchLoginKeyAction = createAsyncThunk(
  'uniKey',
  async (arg, { dispatch }) => {
    await getKey().then((res) => {
      console.log(res.data.unikey, 'uniKey')
      dispatch(changeLoginKey(res.data.unikey))
    })
  }
)

export const fetchLoginQRCodeAction = createAsyncThunk(
  'LoginQRCode',
  async (unikey: string, { dispatch }) => {
    await getQRCode(unikey).then((res) => {
      console.log(res.data.qrimg, 'LoginQRCode')
      dispatch(changeLoginQRCode(res.data.qrimg))
    })
  }
)

export const fetchLoginQRCodeStatusAction = createAsyncThunk(
  'LoginQRCodeStatus',
  async (unikey: string, { dispatch }) => {
    await checkQRCode(unikey).then((res) => {
      console.log(res, 'LoginQRCodeStatus')
      if (res.code === 200) {
        dispatch(changeLoginQRCodeStatus(res.code))
      }
    })
  }
)

type LoginType = {
  unikey: string
  loginQRCode: string
  loginQRCodeStatus: number
}

const initialState: LoginType = {
  unikey: '',
  loginQRCode: '',
  loginQRCodeStatus: 0
}

export const loginStore = createSlice({
  name: 'login',
  initialState,
  reducers: {
    changeLoginKey(state, action) {
      state.unikey = action.payload
    },
    changeLoginQRCode(state, action) {
      state.loginQRCode = action.payload
    },
    changeLoginQRCodeStatus(state, action) {
      state.loginQRCodeStatus = action.payload
    }
  }
})
export const { changeLoginKey, changeLoginQRCode, changeLoginQRCodeStatus } =
  loginStore.actions
export default loginStore.reducer
